package org.tamal;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.Scanner;
import java.util.logging.Logger;

/**
 * This class contains some static methods.
 * @author Tamal Kanti Nath
 */
public final class Util {

    private static final Logger log = Logger.getLogger(Util.class.getName());

    private Util() {
        // Empty
    }

    /**
     * Reads the input stream and returns a string representation of the input
     * stream.
     * @param inputStream The input stream
     * @return the String read from the input stream
     */
    public static String toString(InputStream inputStream) {
        try (Scanner scanner = new Scanner(inputStream)) {
            return scanner.useDelimiter("\\A").next();
        }
    }

    /**
     * Returns HTTP response from HTTP GET or POST.
     * @param url The request URL
     * @param data The HTTP post data
     * @return HTTP response
     * @throws IOException exception
     */
    public static String fetchUrl(String url, String data) throws IOException {
        URLConnection conn = new URL(url).openConnection();
        conn.setConnectTimeout(60000);
        conn.setReadTimeout(60000);
        if (data != null) {
            conn.setDoOutput(true);
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(data);
            out.flush();
        }
        return toString(conn.getInputStream());
    }

    /**
     * This method returns locale from string.
     * @param localeString the locale string
     * @return the converted Locale
     */
    public static Locale convertLocale(String localeString) {
        if (localeString == null || localeString.isEmpty()) {
            return null;
        }
        String[] part = localeString.split("_");
        Locale locale;
        if (part.length == 1) {
            locale = new Locale(part[0]);
        } else if (part.length == 2) {
            locale = new Locale(part[0], part[1]);
        } else if (part.length == 3) {
            locale = new Locale(part[0], part[1], part[2]);
        } else {
            locale = null;
        }
        return locale;
    }

}
